package com.farm.learn.controller;

import com.farm.learn.domain.UserClass;
import com.farm.learn.service.ClasstServiceInter;
import com.farm.learn.service.PlaytimeServiceInter;
import com.farm.learn.service.UserclassServiceInter;
import com.farm.report.FarmReport;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import com.farm.web.easyui.EasyUiUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.authority.domain.Organization;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuerys;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.ResultsHandle;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：用户课程控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/userclass")
@Controller
public class UserclassController extends WebUtils {
	private final static Logger log = Logger.getLogger(UserclassController.class);
	@Resource
	private UserclassServiceInter userClassServiceImpl;
	@Resource
	private ClasstServiceInter classTServiceImpl;
	@Resource
	private PlaytimeServiceInter playTimeServiceImpl;
	@Resource
	private OrganizationServiceInter organizationServiceImpl;

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(DataQuery query, String classid, String orgid, String classids,
			HttpServletRequest request) {
		playTimeServiceImpl.loadPlayCache();
		try {
			query = EasyUiUtils.formatGridQuery(request, query);
			if (StringUtils.isNotBlank(classid)) {
				query.addRule(new DBRule("a.CLASSID", classid, "="));
			} else {
				if (StringUtils.isNotBlank(classids)) {
					DataQuerys.wipeVirusNoDot(classids);
					query.addSqlRule(" and a.CLASSID in (" + DataQuerys.getWhereInSubVals(parseIds(classids)) + ")");
				}
			}
			DBRule orgidRule = query.getAndRemoveRule("ORGID");
			if (orgidRule != null) {
				orgid = orgidRule.getValue();
			}
			if (StringUtils.isNotBlank(orgid)) {
				Organization org = organizationServiceImpl.getOrganizationEntity(orgid);
				query.addRule(new DBRule("D.TREECODE", org.getTreecode(), "like-"));
			}

			DataResult result = userClassServiceImpl.createUserclassSimpleQuery(query).search();
			final Map<String, Integer> classMaxTimes = new HashMap<String, Integer>();
			result.runHandle(new ResultsHandle() {
				@Override
				public void handle(Map<String, Object> row) {
					String classid = (String) row.get("CLASSID");
					if (!classMaxTimes.containsKey(classid)) {
						// 加载课程总时间，确保在计算用户学习时间合计时不会超管总时间
						classMaxTimes.put(classid, classTServiceImpl.getClassAllTime(classid));
					}
					row.put("PLAYTIME", (Integer) playTimeServiceImpl.getClassLeanTime((String) row.get("CLASSID"),
							(String) row.get("USERID"), classMaxTimes.get(classid)));
				}
			});
			result.runformatTime("ETIME", "yyyy-MM-dd HH:mm");
			result.runformatTime("STIME", "yyyy-MM-dd HH:mm");
			result.runformatTime("LTIME", "yyyy-MM-dd HH:mm");
			result.runDictionary("1:自主学习,2:强制学习", "LEARNTYPE");
			result.runDictionary("2:学习中,3:完成", "PSTATE");
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 下载文件
	 * 
	 * @return
	 */
	@RequestMapping("/exportExcel")
	public void download(String ruleText, String classid, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(5000);
			query.setNoCount();
			query.setRuleText(ruleText);
			Map<String, Object> result = queryall(query, classid, null, null, request);
			FarmReport.newInstance("userClass.xls").addParameter("result", result.get("rows")).generateForHttp(response,
					"userClass");
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	/**
	 * 下载文件
	 * 
	 * @return
	 */
	@RequestMapping("/exportClassExcel")
	public void downloadClassUsers(String classids, String orgid, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(5000);
			query.setNoCount();
			Map<String, Object> result = queryall(query, null, orgid, classids, request);
			FarmReport.newInstance("userClass.xls").addParameter("result", result.get("rows"))
					.addParameter("message",
							query.getPagesize() <= ((List) result.get("rows")).size()
									? "本报表仅展示前" + query.getPagesize() + "条记录"
									: "")
					.generateForHttp(response, "userClass");
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(UserClass entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = userClassServiceImpl.editUserclassEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 重构用户学习状态
	 * 
	 * @param entity
	 * @param session
	 * @return
	 */
	@RequestMapping("/refrashLearnStat")
	@ResponseBody
	public Map<String, Object> refrashLearnStat(String ids, HttpSession session) {
		try {
			for (String userClassId : parseIds(ids)) {
				userClassServiceImpl.refrashLearnStat(userClassId);
			}
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(UserClass entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			// entity = userClassServiceImpl.insertUserclassEntity(entity,
			// getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/adduser")
	@ResponseBody
	public Map<String, Object> adduser(String userid, String classid, HttpSession session) {
		try {
			for (String cid : parseIds(classid)) {
				for (String id : parseIds(userid)) {
					try {
						userClassServiceImpl.bindUserClass(cid, id, getCurrentUser(session));
					} catch (Exception e) {
						log.error(e.getMessage());
					}
				}
				classTServiceImpl.freshLearUserNum(cid);
			}
			return ViewMode.getInstance().setOperate(OperateType.ADD).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				String classid = userClassServiceImpl.getUserclassEntity(id).getClassid();
				userClassServiceImpl.deleteUserclassEntity(id, getCurrentUser(session));
				classTServiceImpl.freshLearUserNum(classid);
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("learn/UserclassResult");
	}

	@RequestMapping("/innerlist")
	public ModelAndView innerlist(String classid, HttpSession session) {
		return ViewMode.getInstance().putAttr("classid", classid).putAttr("cnum", parseIds(classid).size())
				.returnModelAndView("learn/UserclassResultInner");
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(RequestMode pageset, String ids) {
		try {
			switch (pageset.getOperateType()) {
			case (0): {// 查看
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", userClassServiceImpl.getUserclassEntity(ids))
						.returnModelAndView("learn/UserclassForm");
			}
			case (1): {// 新增
				return ViewMode.getInstance().putAttr("pageset", pageset).returnModelAndView("learn/UserclassForm");
			}
			case (2): {// 修改
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", userClassServiceImpl.getUserclassEntity(ids))
						.returnModelAndView("learn/UserclassForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("learn/UserclassForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("learn/UserclassForm");
		}
	}
}
